package jaeger

import (
	"io"

	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/pkg/defers"
	zap2 "gitee.com/zawei/yggdrasil/pkg/log"
	"github.com/opentracing/opentracing-go"
	jconfig "github.com/uber/jaeger-client-go/config"
	"go.uber.org/zap"
)

func newTracer(cfg *Config) (opentracing.Tracer, io.Closer) {
	configuration := jconfig.Configuration{
		ServiceName:         cfg.ServiceName,
		Sampler:             cfg.Sampler,
		Reporter:            cfg.Reporter,
		RPCMetrics:          cfg.RPCMetrics,
		Headers:             cfg.Headers,
		BaggageRestrictions: cfg.BaggageRestrictions,
		Throttler:           cfg.Throttler,
		Tags:                cfg.Tags,
	}
	tracer, closer, err := configuration.NewTracer(cfg.options...)
	if err != nil {
		zap2.Fatal("new jaeger", zap.Error(err))
	}
	return tracer, closer
}

func init() {
	lg := zap2.With(zap2.FieldMod("trace.jaeger"))
	cfg := &Config{}
	if err := config.Get("trace", "jaeger").Scan(cfg); err != nil {
		lg.Panic("fault to load config")
	}
	cfg.WithOption(jconfig.Logger(&logger{lg: lg}))
	tracer, closer := cfg.Build()
	defers.Register(func() error {
		return closer.Close()
	})
	opentracing.InitGlobalTracer(tracer)
}
